<template>
  <div>
      <el-col :span="8">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <el-button style="float: right; padding: 3px 0" type="text" @click="toRegister">注册</el-button>
          </div>
          <el-form ref="loginForm" :model="form" :rules="rules" label-width="80px">
            <el-form-item label="用户名：" prop="name">
              <el-input prefix-icon="el-icon-user" v-model="form.name"/>
            </el-form-item>
            <el-form-item label="密码：" prop="password">
              <el-input :type="isOpen ? 'text' : 'password'" prefix-icon="el-icon-lock" v-model="form.password" @keyup.enter.native="checkForm('loginForm')"/>
              <i :class="isOpen ? iconOpen : iconClose" style="position: absolute; right: 1rem; top: 1rem;" @click="isOpen=!isOpen" @mouseenter="isOpen=!isOpen"></i>
            </el-form-item>
            <el-form-item>
              <el-button type="success" @click="checkForm('loginForm')">登录</el-button>
              <el-button type="primary" @click="resetForm('loginForm')">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        form: {
          name: "",
          password: ""
        },
        status: "register",
        result: {},
        iconOpen: 'glyphicon glyphicon-eye-open',
        iconClose: 'glyphicon glyphicon-eye-close',
        isOpen: false,
        rules: {
          name: [
            {required: true, message: '用户名不能为空', trigger: 'blur'}
          ],
          password: [
            {required: true, message: '密码不能为空', trigger: 'blur'}
          ]
        }
      };
    },
    methods: {
      toRegister() {
        this.$router.push({path: "/register"});
      },
      checkForm(formName) {
        this.$refs[formName].validate(valid => {
          if(valid) {
            this.login();
          } else {
            this.$message.warning('请填写完整的信息！')
            return false;
          }
        })
      },
      login() {
        this.$http({
          method: "get",
          url: `/user/login`,
          params: {
            name: this.form.name,
            password: this.form.password
          }
        }).then(response => {
            this.result = response.data;
            if(this.result.hasOwnProperty('error')) {
              this.$message.error(this.result['error']);
            } else {
              this.$message.success(this.result['success'])
              this.$router.push({path: "/bigScreen"});
            }
          }).catch(err => {
            console.log(err);
          });
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      }
    }
  };
</script>
